<?php
/**
 * Easthv Zend Framework Project
 *
 * LICENSE:
 *
 * @category   Zend
 * @package    Zend_Easthv
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
*/

/**
 * File operations related functions collection
 *
 * Eg. /opt/docs/test.txt
 * fileName : test
 * fileExt : txt
 * fileFullName : test.txt
 * filePath : /opt/docs/test.txt
 * path : /opt/docs/
 *
 * @category   Zend
 * @package    Zend_Easthv
 * @copyright  Copyright (c) 2009-2010 Easthv Team @ East Hui Van Business Consulting Co., Ltd.(http://www.easthv.com)
 * @license    http://framework.zend.com/license/   BSD License
 * @version    1.0
 * @link       http://www.easthv.com
 * @since      1.0
 * @deprecated
 */
class Zend_Easthv_File
{

    /**
     * Get file extension 
     *
     * @access public
     * @param string $name  file name string
     *
     * @return string file extension
     */    
    public static function getExtension($fileFullName)
    {
        return strtolower(end(explode(".", $fileFullName)));
    }

    /**
     * Get file name (Not including extension) 
     *
     * @access public
     * @param string $name  file name string
     *
     * @return string file basename
     */    
    public static function getFileName($fileFullName)
    {
        $nameArray = explode(".", $fileFullName);
        
        if(count($nameArray) == 1){
            return $fileFullName;
        }
        
        array_pop($nameArray);
        return implode(".", $nameArray);
	}

    public static function getFileFullName($filePath)
	{
		$path = dirname($filePath);
		return substr($filePath, strlen($path) + 1);
    }
    
    /**
     * Filter out upload file name
     * Characters are not allowed will replace into _
     *
     * @access public
     * @param string $name  file name string
     *
     * @return string filtered file name
     */    
    public static function filterFileName($fileFullName)
    {
        return preg_replace('/[^.-_0-9a-zA-Z]/', '_', $fileFullName);
    }

    /**
     * Get CRC32 hash for a file
     *
     * @access public
     * @param string $name  file name string
     *
     * @return string crc32 encoding file name
     */    
    public static function getCrc32($filePath)
    {
        $crc32 = hash_file('CRC32', $filePath, false);
        return $crc32 < 0 ? -$crc32 : $crc32;
    }
    
    /**
     * Make dir by full path
     *
     * @access public
     * @param string $dirName dir path string
     *
     * @return void
     */    
    public static function makeDir($dirName, $mode = 0777)
    {
		if(mkdir($dirName, $mode) === true && chmod($dirName, $mode) === true) {
			return true;
		}

		throw new Exception('Made Dir failed.');
	}

	/**
	 * Delete dir
	 *
	 * @access public
	 * @param string $path file or dir path string
	 *
	 * @return boolean if write file complete return true ,failed throw a extension
	 * @throws extension
	 */    
	public static function deleteDir($path)
	{
		if (!file_exists($path)) {
			return false;
		}

		if (@rmdir($path) === false && is_dir($path)) {

			if ($handle = opendir($path)) {

				while (false !== ($file = readdir($handle))) {

					if (is_dir($path.'/'.$file) && $file!='.' && $file!='..') {

						self::deleteDir($path.'/'.$file);

					} else {

						if ($file != '.' && $file != '..') {

							unlink($path.'/'.$file);
						}
					}
				}

				closedir($handle);

			} else {

				throw new Exception('No delete dir permission');

			} 
		}    

		if (is_dir($path)) {

			@rmdir($path);
			return true;

		} else {

			@unlink($path);
			return true;
		}    

	}

    /**
     * Copy file from one path to another
     *
     * @access public
     * @param string $src src file path string
     * @param string $dst dst file path string
     *
     * @return boolean if copy file complete return true ,failed return false
     */    
    public static function copyFile($srcFilePath, $dstFilePath)
    {
        if (!file_exists($srcFilePath)) {
            throw new Exception('Copy file source not exist.');
        }

        if (!copy($srcFilePath, $dstFilePath)) {
            throw new Exception('Copy file failed.');
        }

        return true;
    }

    /**
     * Write content into a file
     *
     * @access public
     * @param string $filename file path string
     * @param string $content content string
     *
     * @return boolean if write file complete return true ,failed throw a extension
     * @throws extension
     */    
    public static function writeFile($filePath, $content)
    {
        if (!$handle = fopen($filePath, 'w')) {
            throw new Exception("File open failed");
        }

        if (fwrite($handle, $content) === false) {
            throw new Exception("File write failed");
        }

        @fclose($handle);
        return true;
    }
    
	/**
     * file list 
     *
     * @access public
	 * @param array $params array(
	 *                      	'dir' => dir path
	 *                      	'sortby' => sortby fileName|fileType|fileSize|updateTime|filePermission|fileOwner
	 *                      	'order' => order
	 *                      	'fileType' => file|dir
	 *                      	'showAll' => true show both General Files and Hidden Files 
	 *                      				 false shhow only General Files 
	 *                      )
	 *
	 * @return array files info array 
	 * @throws extension
	 */    
	public static function getFileList($params)
	{
		$dir = $params['dir'];

		if (!is_dir($dir)) {
			throw new Exception($dir . " is not a dir");
		}

		$handle=opendir($dir);

		while ($file =readdir($handle)) {

			if ($file == '.' || $file == '..') {
				continue;
			}

			if (!$params['showAll'] && preg_match('/^\..*|~$/',$file) ) {
				continue;
			}
			
			if ($params['fileType'] == 'dir' && !is_dir($dir . '/' . $file)) {
				continue;
			}
			
			if ($params['fileType'] == 'file' && is_dir($dir . '/' . $file)) {
				continue;
			}
			
			$files[] = array(
				'fileName' => $file,
				'fileType' => filetype($dir . '/' . $file),
				'fileSize' => filesize($dir . '/' . $file),
				'updateTime' => filemtime($dir . '/' . $file),
				'filePermission' => fileperms($dir . '/' . $file),
				'fileOwner' => fileowner($dir . '/' . $file),
			);
		}

		closedir($handle); 

		if ($params['order'] && $params['sortby'] && $files) {
			$files = Zend_Easthv_Array::multiSortArray($files, $params['sortby'], 'SORT_' . $params['order']);
		}

		return $files;
	}

	/**
     * unzip files 
     *
     * @access public
	 * @param array 
	 *
	 * @return array files info array 
	 * @throws extension
	 */    
	public static function unzip($zipPath, $destDir, $option = 'xzf')
	{
		if (!$zipPath || !file_exists($zipPath)) {
			throw new Exception('Zip ' . $zipPath . " is not exist");
		}
		
		if (!$destDir || !file_exists($destDir)) {
			throw new Exception('Dir ' . $destDir . " is not exist");
		}

		$command = "tar $option $zipPath -C $destDir";
	
		system($command, $retval);

		if ($retval == 0) {
			return true;
		} else {
			return false;
		}
	}
}
